package ru.dc.gui.swing;

import org.jdesktop.swingx.JXTable;
import org.jdom.JDOMException;
import ru.dc.Application;
import ru.dc.object.ServerInfo;
import ru.swing.html.Binder;
import ru.swing.html.css.SelectorGroup;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.HashMap;

/**
 * <pre>
 * User: Penkov Vladimir
 * Date: 01.11.2010
 * Time: 12:06:08
 * </pre>
 */
public class ConnectionList extends Tab {

    private JXTable connectionsTable;

    public ConnectionList() {

        connectionsTable = new JXTable();

        ConnectionsTableModel model = new ConnectionsTableModel();
        connectionsTable.setModel(model);
        connectionsTable.setEditable(false);
        model.refresh();

        connectionsTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount()==2 && SwingUtilities.isLeftMouseButton(e)) {
                    int row = connectionsTable.rowAtPoint(e.getPoint());
                    int modelRow = connectionsTable.convertRowIndexToModel(row);
                    ConnectionsTableModel model = (ConnectionsTableModel) connectionsTable.getModel();
                    ServerInfo si = model.getConnections().get(modelRow);
                    final MainFrame mainFrame = Application.getApplication().getMainFrame();
                    if (mainFrame.containsTab(si)) {
                        mainFrame.selectTab(si);
                    }
                    else {
                        mainFrame.addHubConnectionTab(si);
                    }
                }
            }
        });


        HashMap<SelectorGroup, JComponent> substitutions = new HashMap<SelectorGroup, JComponent>();
        substitutions.put(new SelectorGroup("#connections"), connectionsTable);
        try {
            Binder.bind(this, true, substitutions);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
